package plus.feifei.interactive.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SqlDao {
    private SqlHelper helper;
    private SQLiteDatabase read;
    private SQLiteDatabase write;
    private Context context;
    public SqlDao(Context context){
        this.helper=new SqlHelper(context);
        read=helper.getReadableDatabase();
        write=helper.getWritableDatabase();
    }

    public Context getContext() {
        return context;
    }

    /**
     *  执行sql语句,包括增删改
     */
    public void exeSQL(String sql){
        write.execSQL(sql);
    }



    /**
     * 查询语句
     */
    public JSONArray select(String sql){
        Cursor cursor = read.rawQuery(sql, null);
        JSONArray jsonArray = new JSONArray();
        while (cursor.moveToNext()){
            int columnCount = cursor.getColumnCount();
            JSONObject jsonObject = new JSONObject();
            for (int i = 0; i < columnCount; i++) {
                String columnName = cursor.getColumnName(i);
                String string = cursor.getString(i);
                jsonObject.put(columnName,string);
            }
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }
}
